package com.rimi.shiro;

import com.rimi.bean.User;
import com.rimi.model.dto.LoginDto;
import com.rimi.service.UserService;
import com.rimi.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author liHaiYang
 * @version V1.0
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/7/2 9:56
 */
public class BearerRealm extends MysqlRealm{

    @Autowired
    UserService userService;



    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof BearerToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
             String bearerToken = (String) token.getPrincipal();

        try {
            LoginDto decode = JwtUtil.decode(LoginDto.class, bearerToken);

            if(decode != null){
                //获取过期时间
                Date exp = decode.getExp();
                if(System.currentTimeMillis() <= exp.getTime()){
                    //token没过期

                    //查询数据库，校验token正确性
                    User user = userService.findUserByUserId(decode.getId());

                    if(user != null){
                        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,null,getName());
                        return simpleAuthenticationInfo;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            throw new AuthenticationException("token校验失败");
    }

    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {

    }
}
